import React from 'react';
import './App.less';
import {BrowserRouter as Router, Route, Switch} from 'react-router-dom';
import { routes } from './constant/router';
import RouterMiddleware from "./components/middleware/router.middleware";

export default class App extends React.Component {
    constructor(props) {
        super(props);

        this.state = {
            hasError: false,
        }
    }

    static getDerivedStateFromError (error) {
        return {
            hasError: true,
        };
    }

    componentDidCatch (error, errorInfo) {
        this.setState({ hasError: true });

        console.log(error, errorInfo);
    }

    render() {
        const { hasError } = this.state;

        if (hasError) {
            return <h1>something went wrong!</h1>;
        }
        return (
            <div className="App">
                <Router>
                    <Switch>
                        {
                            routes.map(C => {
                                const Component = C.component;
                                return (
                                    <Route
                                        key={C.path}
                                        exact path={String(C.path)}
                                        render={(props) =>{
                                            return (
                                                <RouterMiddleware {...Object.assign({}, props, this.props)}>
                                                    <Component />
                                                </RouterMiddleware>
                                            )
                                        }}
                                    />
                                );
                            })
                        }
                    </Switch>
                </Router>
            </div>
        );
    }
}
